from multiprocessing import Process, Manager
import multiprocessing.shared_memory as shm
import cv2
import numpy as np
import json

def consumer(lock):
    # image = cv2.imread(r'aaaa.jpg')
    # barrier.wait()  # 等待生产者
    shm_img = shm.SharedMemory(name="SyncImg")
    with lock:
        # img_bytes = bytes(shm_img.buf[:image.nbytes])  # 读取图片
        # img_np = np.ndarray(image.shape, dtype=np.uint8, buffer=img_bytes)
        # 
        meta_bytes = bytes(shm_img.buf).split(b'\x00')[0]  # 截取有效字典数据
        # meta_bytes = bytes(shm_img.buf).split(b'\x00')
        # print(meta_bytes)
        # with open("bbb.txt",'w') as f :
        #     for x in meta_bytes:
        #         f.write(str(x))
        meta_dict = json.loads(meta_bytes.decode())  # 还原字典
        print(meta_dict)
        meta_bytes = json.dumps(meta_dict).encode()  # 序列化字典
        print(len(meta_bytes))
        meta_dict['size']
        img_bytes = bytes(shm_img.buf[len(meta_bytes):meta_dict['size'] + len(meta_bytes)])  # 读取图片
        img_np = np.ndarray(meta_dict['shape'], dtype=np.uint8, buffer=img_bytes)
        for xx in range(img_np.shape[0]):
        
        # img_np = np.ndarray((1440, 2560, 3), dtype=np.uint8, buffer=shm_img.buf[:])
            cv2.imwrite(f"bbb{xx}.jpg",img_np[xx])
    #     cv2.imshow("Image", img_np)
    # cv2.waitKey(0)
    shm_img.close()

if __name__ == "__main__":
    with Manager() as manager:
        # barrier = manager.Barrier(2)
        shared_dict = manager.dict()
        lock = manager.Lock()
        consumer(lock)
